import React, {useState} from 'react'
import { Button, Form, Input, Upload, message, Switch, Tooltip, Select, InputNumber } from 'antd';
import { LoadingOutlined, PlusOutlined, MinusCircleOutlined, UploadOutlined, DeleteOutlined, DownOutlined } from '@ant-design/icons';
import axios from 'axios';  // 数据请求
import { useQuill } from 'react-quilljs';  // 富文本编辑器的内容
import 'quill/dist/quill.snow.css'; // 富文本的样式
import skuStyle from './index.module.scss'



/**
 * 
 * 商品名称
 * 商品的价格
 * 商品的图片
 * 商品的轮播图
 * 商品的规格
 * 商品的描述
 * 商品的详情
 * 商品库存
 */
// 定义了叫  base64 的函数
const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};
const { Option } = Select;

export default function PageAdd(props) {
  const [loading, setLoading] = useState(false);   // 商品主图上传状态
  const [imageUrl, setImageUrl] = useState();  // 商品主图url
  const [fileList, setFileList] = useState([]); // 商品轮播图
  const { quill, quillRef } = useQuill();    // 富文本编辑器
  const [form] = Form.useForm(); // 表单数据绑定
  const [hasSku, setHasSku] = useState(false);  // 是否有规格
  const [sku,setSku] = useState([
    {
      k: '',
      k_s: 's1',
      v: [
        {
          id: 1,
          name: '',
          imgUrl: '',
          loading: false
        }
      ]
    }
  ])
  const [list, setList] = useState([{}])
  const [banner,setBanner] = useState([])



  // 表单验证通过
  const onFinish = (values) => {
   let data = values
   data.banner = banner
   data.mainImage = imageUrl
   data.hasSku = hasSku
   data.sku = {}
   data.sku.tree = sku
   data.sku.list = list
   data.detail = quill.root.innerHTML
   axios.post('/api/goodsAdd', data).then((data)=>{
    if (data.data.code ===200) {
      message.info('新增成功')
      setTimeout(()=>{
        props.history.push('/goods')
      },2000)
    }
   })

  };
  // 表单验证失败
  const onFinishFailed = (errorInfo) => {
    console.log('失败:', errorInfo);
  };


  // 商品主图
  // 商品主图上传
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  
    if (!isJpgOrPng) {
      message.error('请上传 JPG/PNG 文件!');
    }
  
    const isLt2M = file.size / 1024 / 1024 < 2;
  
    if (!isLt2M) {
      message.error('图片不可超过2MB!');
    }
  
    return isJpgOrPng && isLt2M;
  };
  // 商品主图变化
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }

    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false);
        setImageUrl(info.file.response.imgUrl);
      });
    }
  };
  // 商品主图的按钮
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        商品主图
      </div>
    </div>
  );
  // 商品主图结束


  // 商品的轮播图

  // 商品的轮播图上传按钮
  const bannerUploadButton = (
    <div>
      <PlusOutlined />
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传
      </div>
    </div>
  );
  // 商品轮播图发生变化
  const bannerChange = ({ fileList: newFileList, file }) => {
    setFileList(newFileList)
    if(file.status === 'done') {
      console.log(file.response);
      let newBanner = JSON.parse(JSON.stringify(banner))
      newBanner.push(file.response.imgUrl)
      setBanner(newBanner)
    }
  }

  // 轮播图结束
  
  // 插入编辑器
  const insertToEditor = (url) => {
    const range = quill.getSelection();
   
    quill.insertEmbed(range.index, 'image', url);
  };
  // 编辑器图片上传到服务器
  const saveToServer = async (file) => {
    const body = new FormData();
    body.append('file', file);
    const res = await axios.post('/api/detailUpload', body);
    insertToEditor(res.data.uploadedImageUrl);
  };
  // 编辑器图片
  const selectLocalImage = () => {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
    input.click();

    input.onchange = () => {
      const file = input.files[0];
      saveToServer(file);
    };
  };

  // 编辑器结束


  const beforeSkuImgUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  
    if (!isJpgOrPng) {
      message.error('请上传 JPG/PNG 文件!');
    }
  
    const isLt2M = file.size / 1024 / 1024 < 2;
  
    if (!isLt2M) {
      message.error('图片不可超过2MB!');
    }
  
    return isJpgOrPng && isLt2M;
  };
  // 规格图片发生变化
  const handleSkuImageChange = (info,index,i) => {
    let newSku = JSON.parse(JSON.stringify(sku))
    newSku[index].v[i].loading = true
    setSku(newSku)
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      let newSku = JSON.parse(JSON.stringify(sku))
      newSku[index].v[i].loading = false
      newSku[index].v[i].imgUrl = info.file.response.imgUrl
      setSku(newSku)
    }
  };
  React.useEffect(() => {
    if (quill) {
      quill.getModule('toolbar').addHandler('image', selectLocalImage);
    }
  }, [quill]);





  return (
    <div>
      <h2>
        商品添加
      </h2>
      <Form
        name="basic"
        layout="vertical"
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        form={form}
    >
      {/* 商品名称 */}
      <Form.Item
        label="商品名称"
        name="title"
        rules={[
          {
            required: true,
            message: '请输入商品名称!',
          },
        ]}
      >
        <Input />
      </Form.Item>
      {/* 商品价格 */}
      <Form.Item
        label="商品价格"
        name="price"
        rules={[
          {
            required: true,
            message: '请输入商品价格!',
          },
        ]}
      >
        <Input />
      </Form.Item>
      {/* 商品的主图 */}
      <Form.Item
        label="商品主图"
        name="mainImage"
      > 
          <Upload
            name="mainImage"
            listType="picture-card"
            action="/api/mainImgUpload"
            showUploadList={false}
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imageUrl ? (
              <img
                src={imageUrl}
                alt="avatar"
                style={{
                  width: '100%',
                }}
              />
            ) : (
              uploadButton
            )}
          </Upload>
      </Form.Item>
      {/* 商品的轮播图 */}
      <Form.Item
        label="商品轮播图"
        name="bannerImage"
      > 
           <Upload
            action="/api/bannerImgUpload"
            listType="picture-card"
            fileList={fileList}
            onChange={bannerChange}
            name="bannerImage"
          >
            {fileList.length >= 8 ? null : bannerUploadButton}
          </Upload>
      </Form.Item>
      
      {/* 规格是否展示 */}
      <Form.Item label="规格" >
        <Switch onChange={(checked)=>{setHasSku(checked)}}></Switch>
      </Form.Item>
      
      {
        hasSku 
        &&
        sku.map((item,index) => {
          return <div className='flex' key={index}>
            <div className={skuStyle.sku}>
            <p className='mb5'> 请输入规格名称</p>
            <Input placeholder="请输入规格名称" value={item.k} onChange={(e)=>{
              let newSku = JSON.parse(JSON.stringify(sku))
              newSku[index].k = e.target.value
              setSku(newSku)
            }}/>


            {
              item.v.map((el,i) => (
                <div key={i} className={`flex mt15 ${skuStyle.detail}`}>
                    <div className={skuStyle.skuText}>规格：</div>
                    <Input placeholder="请输入规格具体名称" value={el.name} onChange={(e)=>{
                      let newSku = JSON.parse(JSON.stringify(sku))
                      newSku[index].v[i].name = e.target.value
                      setSku(newSku)
                    }}/>
                    <Upload
                      name={'skuImg'}
                      listType="picture-card"
                      action="/api/skuImgUpload"
                      showUploadList={false}
                      beforeUpload={beforeSkuImgUpload}
                      onChange={(info)=>{handleSkuImageChange(info,index,i)}}
                    >
                      {el.imgUrl ? (
                        <img
                          src={el.imgUrl}
                          alt="avatar"
                          style={{
                            width: '100%',
                          }}
                        />
                      ) : (
                        <Tooltip title="点击上传规格照片">
                    <div>
                      {el.loading ? <LoadingOutlined /> : <UploadOutlined />}
                    </div>
                  </Tooltip>
                )}
                    </Upload>
                    {
                      item.v.length>1 ? <div onClick={()=>{
                        let newSku = JSON.parse(JSON.stringify(sku))
                        newSku[index].v.splice(i,1)
                        setSku(newSku)
                      }}>
                        <MinusCircleOutlined></MinusCircleOutlined>
                      </div>: null
                    }
                    
                    <Button type="info" shape="circle" icon={< PlusOutlined/>} onClick={()=>{
                      let obj = {
                        id: sku[index].v[i].id+1,
                        name: '',
                        imgUrl: ''
                      }
                      let newSku = JSON.parse(JSON.stringify(sku))
                      newSku[index].v.push(obj)
                      setSku(newSku)
                    }}/>
            </div>
              ))
            }
            </div>
            <div className='flex flex-align-center ml15'>
              <Button className='addSku' type="primary" shape="circle" icon={< PlusOutlined/>} onClick={()=>{
                  let obj = {
                    k: '',
                    k_s: 's' + (index+2),
                    v: [
                      {
                        id: 1,
                        name: '',
                        imgUrl: '',
                        loading: false
                      }
                    ]
                  }
                  let newSku = JSON.parse(JSON.stringify(sku))
                  newSku.push(obj)
                  setSku(newSku)
                }}/>
                {
                  sku.length>1 ? <Button className='addSku ml15' type="info" shape="circle" icon={<DeleteOutlined />} onClick={()=>{
                  let newSku = JSON.parse(JSON.stringify(sku))
                  newSku.splice(index,1)
                  setSku(newSku)
                }}/> : null
                }
              </div>
          </div>
        })
      }
      {
         hasSku
         &&
         (
          <div className='mb15'>
          <p>请选择具体的规格</p>
          {
            list.map((listItem,li) => (
              <div className='flex mt15' key={li}>
                  {
                    sku.map((item,index) => (
                      <div key={index} className="mr15">
                        <Select
                            style={{
                              width: 120,
                            }}
                            defaultValue={`请选择${item.k}`}
                            onChange={(values)=>{
                              let newList = JSON.parse(JSON.stringify(list))
                              let [key,val] = values.split('-')
                              newList[li][key] = val-0
                              setList(newList)
                            }}
                          >
                            {
                              item.v.map((el,i)=> (
                                <Option key={i} value={item.k_s + '-' + el.id}>{el.name}</Option>
                              ))
                            }
                          </Select>
                      </div>
                    ))
                  }
                  <InputNumber className='mr15' min={1} placeholder='库存' onChange={(val)=>{
                     let newList = JSON.parse(JSON.stringify(list))
                     newList[li].stock_num = val
                     setList(newList)
                  }}/>
                  <InputNumber className='mr15' placeholder='价格' min={0.01}  onChange={(val)=>{
                     let newList = JSON.parse(JSON.stringify(list))
                     newList[li].price = val
                     setList(newList)
                  }}/>
                  <Button className='addSku' type="primary" shape="circle" icon={< PlusOutlined/>} onClick={()=>{
                      let newList = JSON.parse(JSON.stringify(list))
                      newList.push({})
                      setList(newList)
                  }}/>
                  {
                    list.length>1 ? <Button className='addSku ml15' type="info" shape="circle" icon={<DeleteOutlined />} onClick={()=>{
                      let newList = JSON.parse(JSON.stringify(list))
                      newList.splice(li,1)
                      setList(newList)
                    }}/> : null
                  }
              </div>
            ))
          }
          
            
          </div>
         )
      }
     
      
      {/* 商品的描述 */}
      <Form.Item
        label="商品描述"
        name="desc"
      >
        <Input />
      </Form.Item>
      {/* 商品的详情 */}
      <Form.Item
        label="商品详情"
        name="detail"
      >
        <div style={{  height: 400 }}>
          <div ref={quillRef} />
        </div>
      </Form.Item>
      <Form.Item className='mt80'>
        <Button type="primary" htmlType="submit">
          添加商品
        </Button>
      </Form.Item>
    </Form>
    </div>
  );
}




